package 使用注解实现简单路由;

import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.*;

// 路由注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Route {
    String path();
}

// 控制器类
class SimpleController {
    @Route(path = "/home")
    public void home() {
        System.out.println("访问首页");
    }
    
    @Route(path = "/about")
    public void about() {
        System.out.println("关于我们");
    }
    
    public void notARoute() {
        System.out.println("这个方法没有路由注解");
    }
}

// 路由处理器
public class AnnotationDemo5 {
    private static Map<String, Method> routeMap = new HashMap<>();
    
    static {
        // 初始化时扫描所有路由
        SimpleController controller = new SimpleController();
        Class<?> clazz = controller.getClass();
        
        for (Method method : clazz.getMethods()) {
            if (method.isAnnotationPresent(Route.class)) {
                Route route = method.getAnnotation(Route.class);
                routeMap.put(route.path(), method);
            }
        }
    }
    
    public static void handleRequest(String path) throws Exception {
        Method method = routeMap.get(path);
        if (method != null) {
            method.invoke(new SimpleController());
        } else {
            System.out.println("404 未找到路由: " + path);
        }
    }
    
    public static void main(String[] args) throws Exception {
        handleRequest("/home");
        handleRequest("/about");
        handleRequest("/contact");
    }
}